const db = require("../db/index"); // 数据库处理模块

// 获取轮播图处理函数
exports.getBanner = (req, res) => {
  const sql = `SELECT * FROM banner`;
  db.query(sql, (err, data) => {
    if (err) return res.send({ code: 501, err });
    res.send({
      code: 200,
      data,
    });
  });
};

// 获取主页分类处理函数
exports.getHomeClassify = (req, res) => {
  const sql = `SELECT * FROM home_classify`;
  db.query(sql, (err, data) => {
    if (err) return res.send({ code: 501, err });
    data[0].tab = JSON.parse(data[0].tab);
    data[0].classify = JSON.parse(data[0].classify);
    res.send({
      code: 200,
      data: data[0],
    });
  });
};

// 获取主页新品的处理函数
exports.getNewGoods = (req, res) => {
  const sql = `SELECT * FROM newgoods`;
  db.query(sql, (err, data) => {
    if (err) return res.send(err);
    res.send({ code: 200, data });
  });
};

// 获取主页新品的处理函数
exports.getHotGoods = (req, res) => {
  const sql = `SELECT * FROM hotgoods`;
  db.query(sql, (err, data) => {
    if (err) return res.send(err);
    res.send({ code: 200, data });
  });
};

// 获取商品详情
exports.getGoodsInfo = (req, res) => {
  const sql = `SELECT * FROM goodslist where id = ${req.query.id}`;
  db.query(sql, (err, data) => {
    if (err) return res.send(err);
    data[0].bannerimg = JSON.parse(data[0].bannerimg);
    data[0].introimg = JSON.parse(data[0].introimg);
    res.send({ code: 200, data });
  });
};

// 获取商品分类
exports.getGoodsClassify = (req, res) => {
  const sql = `SELECT id,goodsnm,img,price,sales FROM goodslist WHERE classify = ${req.query.id}`;
  db.query(sql, (err, data) => {
    if (err) return res.send(err);
    let list = {};
    switch (req.query.id) {
      case "0":
        list.title = "卧室系列";
        break;
      case "1":
        list.title = "客厅系列";
        break;
      case "2":
        list.title = "餐厅系列";
        break;
    }
    list.content = data;
    res.send({ code: 200, data: list });
  });
};
